package com.sidneysimmons.financially;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

public class BaseServer {
	
	private final String CLASS_NAME = this.getClass().getName();
	
	/**
	 * Server base class.
	 */
	public BaseServer() {
		
	}
	
	/**
	 * Sends one value to the supplied destination.
	 * 
	 * @return HttpEntity response
	 */
	public HttpEntity sendValue(String destination, String value) {
		if(destination == null || value == null) {
			return null;
		}

		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
			nameValuePairs.add(new BasicNameValuePair("message", value));
			
			HttpPost httpPost = new HttpPost(destination);
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
			HttpClient httpClient = new DefaultHttpClient();
			Log.d(CLASS_NAME, "Sending: " + value);
			Log.d(CLASS_NAME, "Destination: " + destination);
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			
			return entity;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * Sends multiple values to the supplied destination.  Each value has a 
	 * name paired with it.
	 * 
	 * @return HttpEntity response
	 */
	public HttpEntity sendMultiValue(String destination, List<NameValuePair> pairs) {
		if (destination == null || pairs == null) {
			return null;
		}
		
		try {			
			HttpPost httpPost = new HttpPost(destination);
			httpPost.setEntity(new UrlEncodedFormEntity(pairs));
			
			HttpClient httpClient = new DefaultHttpClient();
			Log.d(CLASS_NAME, "Sending: " + pairs);
			Log.d(CLASS_NAME, "Destination: " + destination);
			HttpResponse response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			
			return entity;
			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
